/**
 * 云打印系统主要JavaScript文件
 */

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化上传区域
    initUploadArea();
    
    // 初始化队列刷新
    initQueueRefresh();
    
    // 初始加载队列状态
    loadQueueStatus();
});

/**
 * 初始化上传区域和相关事件
 */
function initUploadArea() {
    const uploadArea = document.getElementById('uploadArea');
    const fileInput = document.getElementById('fileInput');
    const selectFileBtn = document.getElementById('selectFileBtn');
    
    // 处理拖放事件
    if (uploadArea) {
        uploadArea.addEventListener('dragover', function(e) {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });
        
        uploadArea.addEventListener('dragleave', function() {
            uploadArea.classList.remove('dragover');
        });
        
        uploadArea.addEventListener('drop', function(e) {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            
            if (e.dataTransfer.files.length > 0) {
                handleFiles(e.dataTransfer.files);
            }
        });
    }
    
    // 处理文件选择按钮点击
    if (selectFileBtn && fileInput) {
        selectFileBtn.addEventListener('click', function() {
            fileInput.click();
        });
        
        fileInput.addEventListener('change', function() {
            if (fileInput.files.length > 0) {
                handleFiles(fileInput.files);
            }
        });
    }
}

/**
 * 初始化队列刷新按钮
 */
function initQueueRefresh() {
    const refreshBtn = document.getElementById('refreshBtn');
    if (refreshBtn) {
        refreshBtn.addEventListener('click', loadQueueStatus);
    }
}

/**
 * 处理选择的文件
 * @param {FileList} files - 文件列表
 */
function handleFiles(files) {
    const fileList = document.getElementById('fileList');
    if (!fileList) return;
    
    fileList.innerHTML = '';
    
    for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const fileItem = createFileItem(file);
        fileList.appendChild(fileItem);
        
        uploadFile(file, fileItem);
    }
}

/**
 * 创建文件列表项
 * @param {File} file - 文件对象
 * @returns {HTMLElement} - 文件列表项DOM元素
 */
function createFileItem(file) {
    const fileItem = document.createElement('div');
    fileItem.className = 'file-item';
    
    const fileInfo = document.createElement('div');
    fileInfo.className = 'file-info';
    
    const icon = document.createElement('span');
    icon.className = 'file-icon';
    icon.innerHTML = '<i class="bi bi-file-earmark"></i>';
    
    const name = document.createElement('span');
    name.className = 'file-name';
    name.textContent = file.name;
    
    const size = document.createElement('span');
    size.className = 'file-size';
    size.textContent = formatFileSize(file.size);
    
    fileInfo.appendChild(icon);
    fileInfo.appendChild(name);
    fileInfo.appendChild(size);
    
    const statusIndicator = document.createElement('div');
    statusIndicator.className = 'status-indicator';
    
    const statusIcon = document.createElement('span');
    statusIcon.className = 'status-icon';
    statusIcon.innerHTML = '<div class="loading"></div>';
    
    const statusText = document.createElement('span');
    statusText.className = 'status-text';
    statusText.textContent = '准备上传...';
    
    statusIndicator.appendChild(statusIcon);
    statusIndicator.appendChild(statusText);
    
    fileItem.appendChild(fileInfo);
    fileItem.appendChild(statusIndicator);
    
    return fileItem;
}

/**
 * 上传文件到服务器
 * @param {File} file - 要上传的文件
 * @param {HTMLElement} fileItem - 文件列表项DOM元素
 */
function uploadFile(file, fileItem) {
    const statusIcon = fileItem.querySelector('.status-icon');
    const statusText = fileItem.querySelector('.status-text');
    
    statusText.textContent = '上传中...';
    
    const formData = new FormData();
    formData.append('file', file);
    
    fetch('/api/upload', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            return response.json().then(error => {
                throw new Error(error.detail || '上传失败');
            });
        }
        return response.json();
    })
    .then(data => {
        statusIcon.innerHTML = '<i class="bi bi-check-circle status-success"></i>';
        
        if (data.is_duplicate) {
            statusText.textContent = '文件已存在';
            statusIcon.innerHTML = '<i class="bi bi-exclamation-circle status-warning"></i>';
        } else {
            statusText.textContent = '上传成功';
        }
        
        // 添加打印按钮
        const printBtn = document.createElement('button');
        printBtn.className = 'btn btn-sm btn-primary ms-2';
        printBtn.innerHTML = '<i class="bi bi-printer"></i> 打印';
        printBtn.onclick = function() {
            printFile(data.filename, fileItem);
        };
        
        // 将按钮添加到状态指示器
        const statusIndicator = fileItem.querySelector('.status-indicator');
        statusIndicator.appendChild(printBtn);
        
        // 延迟后刷新队列状态
        setTimeout(loadQueueStatus, 1000);
    })
    .catch(error => {
        statusIcon.innerHTML = '<i class="bi bi-x-circle status-error"></i>';
        statusText.textContent = error.message || '上传失败';
        console.error('Upload error:', error);
    });
}

/**
 * 发送打印请求
 * @param {string} filename - 要打印的文件名
 * @param {HTMLElement} fileItem - 文件列表项DOM元素
 */
function printFile(filename, fileItem) {
    const statusIcon = fileItem.querySelector('.status-icon');
    const statusText = fileItem.querySelector('.status-text');
    const printBtn = fileItem.querySelector('.btn-primary');
    
    if (printBtn) {
        printBtn.disabled = true;
        printBtn.innerHTML = '<div class="loading" style="width:12px;height:12px;"></div> 打印中...';
    }
    
    // 发送打印请求
    fetch('/api/print', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            filename: filename
        })
    })
    .then(response => {
        if (!response.ok) {
            return response.json().then(error => {
                throw new Error(error.detail || '打印失败');
            });
        }
        return response.json();
    })
    .then(data => {
        statusIcon.innerHTML = '<i class="bi bi-printer status-success"></i>';
        statusText.textContent = '打印成功';
        
        if (printBtn) {
            printBtn.remove(); // 移除打印按钮，防止重复打印
        }
        
        showAlert('文件已发送到打印机', 'success');
        
        // 延迟后刷新队列状态
        setTimeout(loadQueueStatus, 1000);
    })
    .catch(error => {
        statusIcon.innerHTML = '<i class="bi bi-x-circle status-error"></i>';
        statusText.textContent = '打印失败';
        
        if (printBtn) {
            printBtn.disabled = false;
            printBtn.innerHTML = '<i class="bi bi-printer"></i> 重试打印';
        }
        
        showAlert('打印失败: ' + (error.message || '未知错误'), 'danger');
        console.error('Print error:', error);
    });
}

/**
 * 加载打印队列状态
 */
function loadQueueStatus() {
    const refreshBtn = document.getElementById('refreshBtn');
    if (refreshBtn) {
        refreshBtn.disabled = true;
        refreshBtn.innerHTML = '<div class="loading" style="width:15px;height:15px;margin-right:5px;"></div> 刷新中...';
    }
    
    fetch('/api/queue')
        .then(response => response.json())
        .then(data => {
            updateQueueStats(data);
            updateQueueList(data.queue_files);
            updateRecentPrints(data.recent_prints);
            
            if (refreshBtn) {
                refreshBtn.disabled = false;
                refreshBtn.innerHTML = '<i class="bi bi-arrow-clockwise"></i> 刷新';
            }
        })
        .catch(error => {
            console.error('Error loading queue status:', error);
            showAlert('无法加载队列状态', 'danger');
            
            if (refreshBtn) {
                refreshBtn.disabled = false;
                refreshBtn.innerHTML = '<i class="bi bi-arrow-clockwise"></i> 刷新';
            }
        });
}

/**
 * 更新队列统计数据
 * @param {Object} data - 队列状态数据
 */
function updateQueueStats(data) {
    const processedCount = document.getElementById('processedCount');
    const printedCount = document.getElementById('printedCount');
    const queueCount = document.getElementById('queueCount');
    const waitingCount = document.getElementById('waitingCount');
    const recentCount = document.getElementById('recentCount');
    
    if (processedCount) {
        processedCount.textContent = data.processed_count || 0;
    }
    
    if (printedCount) {
        printedCount.textContent = data.printed_count || 0;
    }
    
    if (queueCount) {
        queueCount.textContent = data.queue_files ? data.queue_files.length : 0;
    }
    
    // 更新等待打印文件数量
    if (waitingCount) {
        waitingCount.textContent = data.queue_files ? data.queue_files.length : 0;
    }
    
    // 更新最近打印文件数量
    if (recentCount) {
        recentCount.textContent = data.recent_prints ? data.recent_prints.length : 0;
    }
}

/**
 * 更新队列文件列表
 * @param {Array} queueFiles - 队列中的文件列表
 */
function updateQueueList(queueFiles) {
    const queueList = document.getElementById('queueList');
    if (!queueList) return;
    
    queueList.innerHTML = '';
    
    if (!queueFiles || queueFiles.length === 0) {
        const emptyMessage = document.createElement('div');
        emptyMessage.className = 'text-center text-muted py-3';
        emptyMessage.textContent = '没有文件在队列中';
        queueList.appendChild(emptyMessage);
        return;
    }
    
    // 限制显示最近10个文件
    const displayLimit = 10;
    const displayFiles = queueFiles.slice(0, displayLimit);
    const remainingCount = Math.max(0, queueFiles.length - displayLimit);
    
    displayFiles.forEach(file => {
        const fileItem = document.createElement('div');
        fileItem.className = 'file-item';
        
        const fileInfo = document.createElement('div');
        fileInfo.className = 'file-info';
        
        const icon = document.createElement('span');
        icon.className = 'file-icon';
        icon.innerHTML = '<i class="bi bi-file-earmark"></i>';
        
        const name = document.createElement('span');
        name.className = 'file-name';
        name.textContent = file.filename;
        
        const size = document.createElement('span');
        size.className = 'file-size';
        size.textContent = formatFileSize(file.size);
        
        // 添加状态徽章
        const statusBadge = document.createElement('span');
        statusBadge.className = 'badge status-badge status-pending ms-2';
        statusBadge.textContent = '等待中';
        
        fileInfo.appendChild(icon);
        fileInfo.appendChild(name);
        fileInfo.appendChild(size);
        fileInfo.appendChild(statusBadge);
        
        const statusIndicator = document.createElement('div');
        statusIndicator.className = 'status-indicator';
        
        const statusIcon = document.createElement('span');
        statusIcon.className = 'status-icon';
        statusIcon.innerHTML = '<i class="bi bi-hourglass status-pending"></i>';
        
        const statusText = document.createElement('span');
        statusText.className = 'status-text';
        statusText.textContent = file.status || '准备打印';
        
        // 添加时间戳（如果有）
        if (file.time) {
            try {
                const date = new Date(file.time);
                const timeSpan = document.createElement('span');
                timeSpan.className = 'time-stamp text-muted ms-2';
                timeSpan.textContent = date.toLocaleTimeString();
                statusIndicator.appendChild(timeSpan);
            } catch (e) {}
        }
        
        statusIndicator.appendChild(statusIcon);
        statusIndicator.appendChild(statusText);
        
        fileItem.appendChild(fileInfo);
        fileItem.appendChild(statusIndicator);
        
        queueList.appendChild(fileItem);
    });
    
    // 如果有更多文件，显示"查看更多"提示
    if (remainingCount > 0) {
        const moreInfo = document.createElement('div');
        moreInfo.className = 'text-end text-muted mt-2 small';
        moreInfo.textContent = `还有 ${remainingCount} 个文件未显示`;
        queueList.appendChild(moreInfo);
    }
}

/**
 * 更新最近打印记录
 * @param {Array} recentPrints - 最近打印的文件列表
 */
function updateRecentPrints(recentPrints) {
    const recentPrintsList = document.getElementById('recentPrintsList');
    if (!recentPrintsList) return;
    
    recentPrintsList.innerHTML = '';
    
    if (!recentPrints || recentPrints.length === 0) {
        const emptyMessage = document.createElement('div');
        emptyMessage.className = 'text-center text-muted py-3';
        emptyMessage.textContent = '暂无打印记录';
        recentPrintsList.appendChild(emptyMessage);
        return;
    }
    
    // 限制显示最近5个记录
    const displayLimit = 5;
    const displayPrints = recentPrints.slice(0, displayLimit);
    const remainingCount = Math.max(0, recentPrints.length - displayLimit);
    
    displayPrints.forEach(print => {
        const fileItem = document.createElement('div');
        fileItem.className = 'file-item';
        
        const fileInfo = document.createElement('div');
        fileInfo.className = 'file-info';
        
        const icon = document.createElement('span');
        icon.className = 'file-icon';
        icon.innerHTML = '<i class="bi bi-file-earmark-check"></i>';
        
        const name = document.createElement('span');
        name.className = 'file-name';
        name.textContent = print.filename;
        
        // 添加状态徽章
        const statusBadge = document.createElement('span');
        statusBadge.className = 'badge status-badge status-success ms-2';
        statusBadge.textContent = '已打印';
        
        fileInfo.appendChild(icon);
        fileInfo.appendChild(name);
        fileInfo.appendChild(statusBadge);
        
        const statusIndicator = document.createElement('div');
        statusIndicator.className = 'status-indicator';
        
        const statusIcon = document.createElement('span');
        statusIcon.className = 'status-icon';
        statusIcon.innerHTML = '<i class="bi bi-printer status-success"></i>';
        
        const statusText = document.createElement('span');
        statusText.className = 'status-text';
        
        // 格式化时间
        let printTime = '未知时间';
        if (print.time) {
            try {
                const date = new Date(print.time);
                printTime = date.toLocaleString();
            } catch (e) {
                printTime = print.time;
            }
        }
        
        statusText.textContent = `打印于 ${printTime}`;
        
        statusIndicator.appendChild(statusIcon);
        statusIndicator.appendChild(statusText);
        
        fileItem.appendChild(fileInfo);
        fileItem.appendChild(statusIndicator);
        
        recentPrintsList.appendChild(fileItem);
    });
    
    // 如果有更多记录，显示"查看更多"提示
    if (remainingCount > 0) {
        const moreInfo = document.createElement('div');
        moreInfo.className = 'text-end text-muted mt-2 small';
        moreInfo.textContent = `还有 ${remainingCount} 条记录未显示`;
        recentPrintsList.appendChild(moreInfo);
    }
}

/**
 * 显示提示消息
 * @param {string} message - 消息内容
 * @param {string} type - 消息类型 (info, success, warning, danger)
 */
function showAlert(message, type = 'info') {
    const alertsContainer = document.getElementById('alerts');
    if (!alertsContainer) return;
    
    const alert = document.createElement('div');
    alert.className = `alert alert-${type} alert-dismissible fade show`;
    alert.setAttribute('role', 'alert');
    
    alert.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    `;
    
    alertsContainer.appendChild(alert);
    
    // 5秒后自动关闭
    setTimeout(() => {
        alert.classList.remove('show');
        setTimeout(() => {
            alertsContainer.removeChild(alert);
        }, 150);
    }, 5000);
}

/**
 * 格式化文件大小
 * @param {number} bytes - 文件大小（字节）
 * @returns {string} - 格式化后的文件大小
 */
function formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    // 在小屏幕上使用更简洁的格式
    if (window.innerWidth < 576) {
        return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + sizes[i];
    }
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
} 